package com.zhouheng.springbootmultithreading.tuling.jmm.success;

/**
 *
 * Thread.yield()  yield /jiːld/ 亿藕得
 *
 * 线程会释放时间片，上下文切换，其他线程执行期间，while(true)本地内存过期清除了，
 * 重新获取时间片时，加载上下文，本地内存没有会重新去主内存中加载最新的值
 * 上下文切换会大量占用时间，要避免频繁的上下文切换
 *
 */
public class VisibilitySuccessTest3 {

    private boolean flag = true;
    private int count = 0;

    public void refresh() {
        flag = false;
        System.out.println(Thread.currentThread().getName() + "修改flag:" + flag);
    }

    public void load() {
        System.out.println(Thread.currentThread().getName() + "开始执行.....");
        while (flag) {
            //TODO  业务逻辑
            count++;
            // yield放弃时间片
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + "跳出循环: count=" + count);
    }

    public static void main(String[] args) throws InterruptedException {
        VisibilitySuccessTest3 test = new VisibilitySuccessTest3();

        // 线程threadA模拟数据加载场景
        Thread threadA = new Thread(() -> test.load(), "threadA");
        threadA.start();

        // 让threadA执行一会儿
        Thread.sleep(1000);
        // 线程threadB通过flag控制threadA的执行时间
        Thread threadB = new Thread(() -> test.refresh(), "threadB");
        threadB.start();
    }

}
